<template>
    <div class="material" @click="addTag = false">
        <a-layout style="height: 100%">
            <a-layout-header class="mate-head">
                <a-tabs v-model:activeKey="tabKey" @change="tabKeyFun">
                    <a-tab-pane
                        :key="item.value"
                        :tab="item.name"
                        v-for="item in userType !== 's' ? tabList : tabList1"
                    ></a-tab-pane> </a-tabs
            ></a-layout-header>
            <a-layout class="mate-box">
                <a-layout-sider class="mate-box-menu">
                    <div class="mate-box-menu-item">
                        <a-menu
                            mode="inline"
                            style="background: #fff; height: 100%"
                            theme="light"
                            v-model:openKeys="openKeys"
                            v-model:selectedKeys="selectedKeys"
                        >
                            <template v-if="userType !== 's'">
                                <a-sub-menu
                                    :key="item.picTypeClass"
                                    v-for="(item, index) in materialList"
                                    :inlineIndent="1"
                                    @click="menuSele(index)"
                                >
                                    <template #title> {{ item.picTypeClass == '0' ? '图片素材' : '视频素材' }}</template>
                                    <a-menu-item
                                        :key="item1.picTypeCode"
                                        v-for="item1 in item.data"
                                        :inlineIndent="2"
                                        @click="menuItemFun(item1, item.picTypeClass)"
                                    >
                                        <div><FolderOpenOutlined /> {{ item1.picTypeCname }}</div>
                                        <div v-if="item1.picTypeCode == selectedKeys[0]" style="width: 40px">
                                            <EditOutlined @click.stop="editFun" />
                                            <DeleteOutlined @click.stop="delFun" v-if="item.size == 0" />
                                        </div>
                                        <div v-else style="width: 40px">{{ item1.size }}</div>
                                    </a-menu-item>
                                </a-sub-menu>
                            </template>
                            <template v-if="userType == 's'">
                                <a-menu-item
                                    :key="item.picTypeCode"
                                    v-for="item in materialList"
                                    :inlineIndent="0"
                                    @click="menuItemFun(item, tabKey)"
                                    style="display: flex; justify-content: space-between; align-items: center"
                                >
                                    <div><FolderOpenOutlined /> {{ item.picTypeCname }}</div>
                                    <div v-if="item.picTypeCode == selectedKeys[0]" style="width: 40px">
                                        <EditOutlined @click.stop="editFun(item)" />
                                        <DeleteOutlined @click.stop="delFun(item)" v-if="item.size == 0 || tabKey == 1" />
                                    </div>
                                    <div v-else style="width: 40px">{{ item.size }}</div>
                                </a-menu-item>
                            </template>
                        </a-menu>
                    </div>
                    <div class="addClassify" @click="addClassify" v-if="tabKey == 1 || userType == 's'">
                        <FolderOpenOutlined />{{ t('yl.materialUp') }}
                    </div>
                </a-layout-sider>
                <a-layout style="position: relative; background: #fff">
                    <div
                        style="
                            width: 100%;
                            position: absolute;
                            top: 0px;
                            line-height: 50px;
                            padding: 0 20px;
                            display: flex;
                            justify-content: space-between;
                        "
                    >
                        <a-checkbox
                            :disabled="!data.length"
                            @change="onSelectAll($event)"
                            :indeterminate="indeterminate"
                            v-model:checked="checkAll"
                        >
                            选择全部
                        </a-checkbox>

                        <div class="addClassify" @click="upMaterial" v-if="userType == 's' || tabKey == 1">
                            <PlusOutlined />{{ t('yl.materialUp') }}
                        </div>
                    </div>
                    <a-layout-content style="width: 100%; position: absolute; top: 50px; bottom: 60px">
                        <div class="mate-box-tab">
                            <a-table
                                :columns="columns"
                                :data-source="data"
                                :row-selection="rowSelection"
                                :rowKey="setRowKey"
                                class="usertable"
                                ref="table"
                                :showHeader="false"
                                style="height: 100%; overflow: auto; min-height: 500px"
                                :pagination="false"
                            >
                                <template #picUrlItem="{ record }">
                                    <div class="tab-list">
                                        <div class="img">
                                            <a-image v-if="picTypeCode !== '1'" :width="60" :height="60" :src="record.picUrl" />
                                            <video
                                                v-if="picTypeCode == '1'"
                                                style="width: 100px"
                                                :src="record.picUrl"
                                                controls="controls"
                                            >
                                                您的浏览器不支持 video 标签。
                                            </video>
                                        </div>
                                        <div class="tab-list-text">
                                            <div class="tab-title">{{ record.name }}。{{ record.picName }}</div>
                                            <div class="tab-text">
                                                {{
                                                    record.spec.width && record.spec.heigh
                                                        ? record.spec.width + '*' + record.spec.heigh + '|'
                                                        : ''
                                                }}
                                                {{ record.spec.extensionName ? record.spec.extensionName + '|' : '' }}
                                                {{ record.spec.fileSize }}
                                            </div>
                                            <div class="tab-classify">
                                                <span class="tab-classify-text" v-for="pic in record.picLabel" :key="pic">
                                                    {{ pic
                                                    }}<CloseOutlined
                                                        v-if="tabKey == 1 || userType == 's'"
                                                        style="cursor: pointer"
                                                        @click="delTagUp(record, pic)"
                                                    />
                                                </span>

                                                <TagOutlined
                                                    v-if="tabKey == 1 || userType == 's'"
                                                    class="tab-classify-icon"
                                                    @click.stop="addTagFun(record)"
                                                />
                                                <transition name="fade">
                                                    <div class="tab-mode" v-if="record.id == tagId && addTag">
                                                        <a-form :model="formState" ref="formRef">
                                                            <a-form-item
                                                                style="margin-bottom: 0"
                                                                name="opLabel"
                                                                :rules="[
                                                                    {
                                                                        required: true,
                                                                        message: 'Please input your Username!',
                                                                    },
                                                                    {
                                                                        max: 20,
                                                                        message: '最长20位!',
                                                                    },
                                                                ]"
                                                            >
                                                                <a-row :gutter="16">
                                                                    <a-col :span="19">
                                                                        <a-input
                                                                            v-model:value="formState.opLabel"
                                                                            placeholder="标签名称(少于10个字符)"
                                                                        />
                                                                    </a-col>
                                                                    <a-col :span="5">
                                                                        <span
                                                                            style="color: #ff6702; cursor: pointer"
                                                                            @click="setTagUp(record, 'table', '')"
                                                                            >创建</span
                                                                        >
                                                                    </a-col>
                                                                </a-row>
                                                            </a-form-item>
                                                        </a-form>
                                                        <a-row class="tab-gutter-box">
                                                            <a-col
                                                                class="tab-gutter-row"
                                                                :span="24"
                                                                v-for="item in 20"
                                                                :key="item"
                                                                @click="setTagUp(record, 'tag', 'name')"
                                                            >
                                                                <div class="gutter-box" style="padding: 5px 0">水果</div>
                                                            </a-col>
                                                        </a-row>
                                                    </div>
                                                </transition>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                                <template #customTime="{ record }">
                                    <div class="tab-time">
                                        {{ record.createdTime }}
                                        <!-- <VerticalAlignBottomOutlined @click="downloadFun('page', record)" /> -->
                                        <SwapOutlined class="tab-time-sw" @click="handMoveFun('page', record)" />
                                    </div>
                                </template>
                            </a-table></div
                    ></a-layout-content>

                    <div class="mate-footer">
                        <!-- <a-button>取消</a-button> <a-button @click="downloadFun('all', null)">下载</a-button> -->
                        <a-button @click="handMoveFun('all', null)">移动</a-button>
                        <a-button>导出表格</a-button>
                    </div>
                </a-layout>
            </a-layout>
        </a-layout>
        <class-model
            v-if="classMold"
            :visible="classMold"
            :title="classTitle"
            :picTypeClass="picTypeClass"
            :picTypeCname="picTypeCname"
            :classType="classType"
            @submit="handClassSubmit"
        ></class-model>
        <up-model
            v-if="upMold"
            :picTypeCode="picTypeCode"
            :upList="upList"
            :visible="upMold"
            :title="upTitle"
            @submit="handUpSubmit"
        ></up-model>

        <move-model
            v-if="moveMold"
            :upList="moveList"
            :ids="moveIds"
            :visible="moveMold"
            :title="moveTitle"
            @submit="handUpSubmit"
        ></move-model>
    </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, onMounted, computed, createVNode, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import {
    postMaterial,
    postMaterialByType,
    getMaterialTypeList,
    deleteMaterialByIds,
    deleteTypeByTypeCode,
    postAddTag,
    postDelTag,
} from '@/api/material';
import { PaginationQuery } from '@/types/table';
import {
    FundOutlined,
    VerticalAlignBottomOutlined,
    FolderOpenOutlined,
    EditOutlined,
    DeleteOutlined,
    TagOutlined,
    CloseOutlined,
    SwapOutlined,
    PlusOutlined,
} from '@ant-design/icons-vue';
import classModel from './components/classModel.vue';
import upModel from './components/upModel.vue';
import moveModel from './components/moveModel.vue';
import { message, Modal } from 'ant-design-vue';

interface DataItem {
    key: number;
    name: string;
    age: number;
    address: string;
    children?: DataItem[];
}
interface DeptState {}
export default defineComponent({
    name: 'classify',
    components: {
        FundOutlined,
        VerticalAlignBottomOutlined,
        FolderOpenOutlined,
        classModel,
        EditOutlined,
        DeleteOutlined,
        TagOutlined,
        CloseOutlined,
        PlusOutlined,
        upModel,
        SwapOutlined,
        moveModel,
    },
    props: {
        state: {
            type: Object,
            default: () => false,
        },
    },
    setup(props, { emit }) {
        const { t } = useI18n();
        const tabList = [
            { name: '平台素材', value: 0 },
            { name: '我的素材', value: 1 },
        ];
        const tabList1 = [
            { name: '图片素材', value: 0 },
            { name: '视频素材', value: 1 },
            { name: '背景素材', value: 2 },
            { name: '装饰素材', value: 3 },
        ];
        const tabKey = ref(0);
        const columns = [
            {
                title: '',
                dataIndex: 'picUrl',
                slots: { customRender: 'picUrlItem' },
            },
            {
                title: '',
                dataIndex: 'createdTime',
                width: '14%',
                slots: { customRender: 'customTime' },
            },
        ];
        const userType = localStorage.getItem('userType');
        const merchantCode = localStorage.getItem('merchantCode');
        const materialList: any = ref([]);
        const tagId = ref(null);
        const addTag = ref(false);
        // 类型 视频  图片  素材
        const picTypeCode = ref('0');
        const data: any = ref([]);
        const state = reactive({
            indeterminate: false,
            checkAll: false,
            checkedList: ['Apple', 'Orange'],
        });
        const formState = reactive({
            id: 0,
            opLabel: '',
        });
        const state1 = reactive({
            theme: 'dark',
            selectedKeys: [],
            openKeys: ['0'],
        });
        const classify = reactive({
            classMold: false,
            classTitle: '新增分类',
            picTypeClass: '',
            picTypeCname: '',
            picTypeEname: '',
            classType: 'add',
        });
        const upload = reactive({
            upMold: false,
            upTitle: t('yl.materialUp'),
            upList: [],
            upIndex: 0,
        });
        const move = reactive({
            moveMold: false,
            moveTitle: t('yl.materialMove'),
            moveList: [],
            moveIds: [],
        });
        const selectedRowKeys: any = ref([]);
        const setRowKey = (record: { [x: string]: any }) => record.id;

        onMounted(async () => {
            if (userType !== 's') {
                materialFun(merchantCode);
            } else {
                materialTypeList();
            }
            upload.upIndex = 0;
            console.log(userType);
        });
        const onCheckAllChange = (e: any) => {
            Object.assign(state, {
                checkedList: e.target.checked ? data : [],
                indeterminate: false,
            });
        };

        const rowSelection = computed(() => {
            return {
                onSelect: onSelect,
                selectedRowKeys,
            };
        });
        watch(
            () => selectedRowKeys.value,
            (val) => {
                state.indeterminate = !!val.length && val.length < data.value.length;
                state.checkAll = val.length === data.value.length;
            }
        );

        const onSelect = (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
            selectedRowKeys.value = selectedRows.map((item) => item.id);
        };

        const onSelectAll = ($event: any) => {
            // 我在这里监听的事件，应该有更好的方法
            if ($event.target.checked) {
                selectedRowKeys.value = data.value.map((item) => item.id);
                console.log(selectedRowKeys.value);
            } else {
                selectedRowKeys.value = [];
            }
        };
        // 获取侧边导航栏数据不等于系统管理员走的接口
        const materialFun = async (code: string | null) => {
            const { content } = await postMaterial({ createdMerchantCode: tabKey.value == 0 ? 0 : code });
            if (content && content.length) {
                console.log(content);

                if (content[0].data && content[0].data.length) {
                    menuItemFun(content[0].data[0], content[0].picTypeClass);
                    state1.selectedKeys.push(content[0].data[0].picTypeCode);
                }
            }

            materialList.value = content;
        };
        const materialTypeList = async () => {
            const { content } = await getMaterialTypeList(tabKey.value);
            if (content.data && content.data.length) {
                menuItemFun(content.data[0], tabKey.value);
                state1.selectedKeys.push(content.data[0].picTypeCode);
            }

            console.log(content);
            materialList.value = content.data;
        };
        // 根据侧边导航点击事件查找素材
        const menuItemFun = async (item: any, type: string | number) => {
            picTypeCode.value = String(type);
            console.log(item);
            console.log('item2222');
            if (item.picTypeCode) {
                const { content } = await postMaterialByType({ picTypeCode: item.picTypeCode });
                content.forEach((i) => {
                    console.log(i.spec);
                    i.picLabel = i.picLabel ? i.picLabel.split('/') : [];
                    i.spec = i.spec ? JSON.parse(i.spec) : {};
                });
                data.value = content;
            }
        };
        // 头部导航点击事件
        const tabKeyFun = (val: any) => {
            // 如果不是系统管理员  平台进来默认传递0   我的传递当前人员MerchantCode
            // 如果是管理员 换接口传递1-4

            state1.selectedKeys = [];
            data.value = [];
            if (userType !== 's') {
                materialFun(merchantCode);
            } else {
                materialTypeList();
            }
        };
        const addClassify = () => {
            classify.classType = 'add';
            classify.classTitle = t('yl.materialAdd');
            classify.classMold = true;
        };
        const handClassSubmit = () => {
            if (userType !== 's') {
                materialFun(merchantCode);
            } else {
                materialTypeList();
            }
            classify.classMold = false;
        };
        // 编辑
        const editFun = (item: any) => {
            console.log(item);
            classify.classType = 'edit';
            classify.classTitle = t('yl.materialEdit');
            classify.picTypeClass = item.picTypeId;
            classify.picTypeCname = item.picTypeCname;
            classify.classMold = true;
        };
        // 删除分类
        const delFun = (item: any) => {
            if (item.size) {
                return;
            }
            deleteTypeByTypeCode(item.picTypeCode).then((res) => {
                if (userType !== 's') {
                    materialFun(merchantCode);
                } else {
                    materialTypeList();
                }
            });
        };
        const addTagFun = (item: any) => {
            tagId.value = item.id;
            addTag.value = true;
        };
        const formRef = ref();
        // 创建标签
        const setTagUp = (item: any, type: string, name: string) => {
            if (type == 'tag') {
                formState.opLabel = name;
            }
            formRef.value.validate().then(() => {
                formState.id = item.id;
                postAddTag(formState).then((res) => {
                    menuItemFun({ picTypeCode: state1.selectedKeys[0] }, picTypeCode.value);
                    addTag.value = false;
                    formRef.value.resetFields();
                });
            });
        };
        // 删除标签
        const delTagUp = (item: any, name: string) => {
            formState.id = item.id;
            formState.opLabel = name;
            postDelTag(formState).then((res) => {
                menuItemFun({ picTypeCode: state1.selectedKeys[0] }, picTypeCode.value);
                addTag.value = false;
                formState.opLabel = '';
            });
        };
        // 上传素材
        const upMaterial = () => {
            console.log(picTypeCode.value);
            if (userType == 's') {
                upload.upList = materialList.value;
            } else {
                upload.upList = materialList.value[upload.upIndex].data;
            }
            console.log(upload.upList);
            upload.upMold = true;
        };
        const menuSele = (val: any) => {
            upload.upIndex = val;
        };
        const handUpSubmit = (type: string) => {
            if (type == 'submit') {
                // if (userType !== 's') {
                //     materialFun(merchantCode);
                // } else {
                //     materialTypeList();
                // }
                menuItemFun({ picTypeCode: state1.selectedKeys[0] }, picTypeCode.value);
            }
            upload.upMold = false;
            move.moveMold = false;
        };
        // 下载图片
        const downloadFun = (type: string, item: any) => {
            // var alink = document.createElement('a');
            // alink.href = item.picUrl;
            // alink.download = 'pic'; //图片名
            // alink.click();
        };
        // 移动素材
        const handMoveFun = (type: string, item: any) => {
            if (type == 'page') {
                move.moveIds = [];
                move.moveIds.push(item.id);
            } else {
                move.moveIds = selectedRowKeys.value;
            }

            if (userType == 's') {
                move.moveList = materialList.value;
            } else {
                move.moveList = materialList.value[upload.upIndex].data;
            }
            move.moveMold = true;
        };

        return {
            formRef,
            rowSelection,
            data,
            columns,
            ...toRefs(state),
            onCheckAllChange,
            setRowKey,
            ...toRefs(state1),
            ...toRefs(classify),
            ...toRefs(upload),
            ...toRefs(move),

            tabKey,
            t,
            onSelectAll,
            selectedRowKeys,
            onSelect,
            tabList,
            tabList1,
            materialFun,
            materialList,
            menuItemFun,
            userType,
            tabKeyFun,
            merchantCode,
            addClassify,
            handClassSubmit,
            materialTypeList,
            editFun,
            delFun,
            tagId,
            addTag,
            addTagFun,
            formState,
            setTagUp,
            delTagUp,
            upMaterial,
            menuSele,
            picTypeCode,
            handUpSubmit,
            downloadFun,
            handMoveFun,
        };
    },
});
</script>

<style lang="scss">
.material {
    position: relative;
    height: 100%;
    width: 100%;
    .mate-head {
        background: #fff;
        height: auto;
        padding: 0px;
        .ant-tabs {
            text-align: center;
        }

        .ant-tabs-nav .ant-tabs-tab-active,
        .ant-tabs-nav .ant-tabs-tab:hover {
            color: #ff6702;
        }
        .ant-tabs-ink-bar {
            background: #ff6702;
        }
    }
    .mate-box {
        background: #fff !important;
        .mate-box-menu {
            width: 204px;
            height: 100%;
            border-right: 1px solid #f0f0f0;

            background: #fff !important;
            position: relative;

            height: 100%;
            .mate-box-menu-item {
                position: absolute;
                top: 0px;
                bottom: 50px;
                overflow: auto;
                width: 200px;
            }
            .addClassify {
                line-height: 50px;
                height: 50px;
                position: absolute;
                bottom: 0px;
                left: 0;
            }
            .ant-menu-item::after {
                border-right: 3px solid #ff6702;
            }
            .ant-menu-submenu-selected {
                color: #fff;
                background: #ff6702;
                .ant-menu-submenu-arrow::after,
                .ant-menu-submenu-arrow::before {
                    background-image: linear-gradient(to right, #fff, #fff);
                }
            }
            .ant-menu-item-selected {
                color: #ff6702 !important;
                background: none;
            }
            .ant-menu-submenu-active {
                color: #ff6702 !important;
            }

            .ant-menu-item:hover {
                color: #ff6702 !important;
            }
            .ant-menu-submenu-title:hover {
                color: #ff6702;
            }
            .ant-menu-submenu-selected .ant-menu-submenu-title:hover {
                color: #fff !important;
            }
        }
    }

    .mate-box-tab {
        width: 100%;
        height: 100%;
        position: relative;
        // overflow: auto;
    }

    .mate-footer {
        display: flex;
        width: 100%;
        border-top: 1px solid #f0f0f0;
        justify-content: right;
        align-items: center;
        height: 50px;
        position: absolute;
        bottom: 0px;
        left: 0;
        .ant-btn {
            margin-left: 10px;
        }
    }
    .tab-list {
        display: flex;
        .tab-list-text {
            padding-left: 15px;

            .tab-title {
                font-size: 12px;
            }
            .tab-classify {
                position: relative;
                display: flex;
                align-items: center;
                .tab-classify-text {
                    display: inline-block;
                    padding: 2px 12px;
                    border: 1px solid #f0f0f0;
                    border-radius: 20px;
                    margin: 0 2px;
                }
                .tab-classify-icon {
                    font-size: 18px;
                    transform: rotate(-90deg);

                    margin-top: 3px;
                }
                .tab-classify-icon:hover {
                    color: #ff6702;
                }
                .tab-mode {
                    width: 230px;
                    height: 290px;
                    padding: 15px;
                    position: absolute;
                    background: #fff;
                    right: -230px;
                    top: 0;
                    box-shadow: 0px 0px 5px #dadada;
                }
                .tab-gutter-box {
                    height: 200px;
                    overflow: auto;
                    border-top: 1px solid #f1f1f1;
                    margin-top: 10px;
                    padding-top: 10px;
                    .tab-gutter-row {
                        cursor: pointer;
                    }
                    .tab-gutter-row:hover {
                        background: #f1f1f1;
                    }
                }
            }
        }
    }
    .tab-time {
        font-size: 12px;
        color: rgba(153, 153, 153, 100);
        .anticon {
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
        }
        .tab-time-sw {
            margin-left: 10px;
        }
    }
}
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>
